import 'dart:convert';
import 'package:eh_mobile/common/utils/toast/bnw_toast.dart';
import 'package:eh_mobile/common/utils/web_rtc_channel_common.dart';
import 'package:eh_mobile/global.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import '../apis/homepage.dart';
import '../store/user_store.dart';

class WebRtcChannel {
  static WebRtcChannel instance = WebRtcChannel._internal();

  WebRtcChannel._internal();

  factory WebRtcChannel() {
    return instance;
  }

  RTCPeerConnection? sendPeer;
  RTCDataChannel? sendChannel;
  Logger? logger;
  Function? receiveDataBlock;
  Function? receiveUserNameBlock;
  Function? receiveReportBlock;
  Function? receiveDynamicBlock;
  String? bottomRandomStr;
  String? dynamicRandomStr;
  String? systemInfoStr;

  initWebRTC(
      {required String channelId,
      required List iceServers,
      String? systemStr}) async {
    systemInfoStr = systemStr;
    logger = Logger();
    // 创建数据通道 sendPeer
    sendPeer = await createPeerConnection({'iceServers': iceServers});
    // 创建数据通道
    RTCDataChannelInit channelInit = RTCDataChannelInit();
    channelInit.ordered = true;
    sendChannel = await sendPeer?.createDataChannel(
      'sendDataChannel',
      channelInit,
    );
    // 等待 candidate
    sendPeer!.onIceCandidate = (RTCIceCandidate e) {
      if (e.candidate != null) {
        // 通过 ws 发送 candidate 给数据通道的另一端
        Map sendMap = {
          'type': "candidate",
          'channel_id': channelId,
          'candidate': e.toMap()
        };
        Global.websocket.sendMessage(sendMap);
        logger?.d('webRTC发送消息给远端:$sendMap');
      }
    };

    sendPeer!.onIceConnectionState = (RTCIceConnectionState state) {
      logger?.d('sendPeer: onIceConnectionState: state$state');
    };

    // 数据通道接收消息
    sendChannel!.onMessage = (RTCDataChannelMessage data) {
      logger?.d('Received message: ${data.text}');
      if (data.text.isNotEmpty) {
        Map jsonMap = jsonDecode(data.text);
        if (jsonMap['type'] == 'answer' && jsonMap['success'] == true) {
          if (jsonMap['index'] == bottomRandomStr) {
            WebRtcChannelCommon.getHomeBottomCateGoryList(
                jsonMap, receiveDataBlock);
          } else if (jsonMap['index'] == dynamicRandomStr) {
            WebRtcChannelCommon.getHomeDynamicDeviceList(jsonMap, receiveDynamicBlock);
          }
        } else if (jsonMap['type'] == 'ws') {
          if (jsonMap['data']['cmd'] == 'report') {
            Map dataMap = jsonMap['data']['data'];
            if (dataMap.keys.contains('power') ||
                dataMap.keys.contains('light_bright')) {
              WebRtcChannelCommon.getReportCmdData(jsonMap['data'], receiveReportBlock);
            }
          } else if (jsonMap['data']['cmd'] == 'dynamic') {
            if (jsonMap['data']['type'] == 'light') {
              WebRtcChannelCommon.getDynamicCmd(jsonMap, receiveDynamicBlock);
            }
          }
        }
      }
    };

    sendChannel!.onDataChannelState = (RTCDataChannelState state) {
      logger?.d('连接状态：$state');
      if (state == RTCDataChannelState.RTCDataChannelOpen) {
        logger?.d('通道已打开：$state');
        //校验身份
        WebRtcChannelCommon.sendCheckIDInfo(sendChannel);
        String userId = UserStore().userStoreCache.read('userId').toString();
        //发送信息获取底部分类数据
        bottomRandomStr = WebRtcChannelCommon.sendInfoGetCategoryList(
            sendChannel,
            userId: userId);
        //发送获取动态
        dynamicRandomStr =
            WebRtcChannelCommon.sendChannelGetUserName(sendChannel);
      }
    };

    sendPeer!.onConnectionState = (RTCPeerConnectionState state) {
      logger?.d('sendPeer连接状态：$state');
      if (state == RTCPeerConnectionState.RTCPeerConnectionStateFailed) {
        HomepageAPI.createDataChannel(systemInfoStr ?? '').then((res) {
          if (res.keys.contains('statusCode') && res['statusCode'] != 200) {
            BnwToast.showView(Get.context!, infoStr: '服务异常');
          } else {
            String channelId = res['channel_id'];
            List iceServes = res['ice_servers'];
            initWebRTC(channelId: channelId, iceServers: iceServes);
          }
        });
      }
    };

    sendPeer!.onIceGatheringState = (RTCIceGatheringState state) {
      logger?.d('sendPeer候选地址状态：$state');
    };

    //给远端创建提议
    RTCSessionDescription offer = await sendPeer!.createOffer({});
    sendPeer!.setLocalDescription(offer);
    // 发送 offer 给数据通道的另一端
    Map map = {'type': "offer", 'channel_id': channelId, 'desc': offer.toMap()};
    Global.websocket.sendMessage(map);
  }

  // 数据通道关闭
  void closeChannel() {
    sendPeer?.close();
    sendChannel?.close();
  }
}
